<template>
  <div style="background: #F9F9F9; height: 150vh;">
    <!-- 面包屑导航栏 -->
    <div style="margin-left:10%;margin-top: -10px;">
    <AppBreadcrumb :breadcrumbs="breadcrumbs" :breadcrumbItemStyle="breadcrumbItemStyle" />
    </div>
    

    <p style="margin-top: -20px; margin-left: 11vw; font-size: 24px; padding-top: 20px;">新建作业</p>
    <div class="new-assignment">
      <form @submit.prevent="createAssignment">
        <div class="form-group">
          <label for="title"><span class="required">*</span>作业标题</label>
          <input style="width:98%" type="text" v-model="assignmentTitle" id="title" required />
        </div>
        <div style="margin-bottom: 20px;">
          <div class="form-group">
            <label for="content"><span class="required">*</span>作业内容</label>
            <QuillEditor style="height:300px;" v-model="assignmentContent" />
          </div>
          <div class="upload-button-wrapper">
            <input type="file" style="display:none" ref="fileInput" @change="handleFileUpload" id="file" />
            <button type="button" @click="triggerFileUpload" class="upload-button">
              <img src="@/assets/picture/upload.png" alt="上传图标" style="width: 20px; margin-right: 8px;" />上传附件
            </button>
            <span v-if="selectedFileName" class="file-name">{{ selectedFileName }}</span>
          </div>
        </div>
        <div>
          <div class="form-group">
            <label for="answer">参考答案</label>
            <QuillEditor style="height:300px;" v-model="assignmentAnswer" />
          </div>
          <div style="display:flex;flex-direction:row;justify-content: space-between;">
            <div class="upload-button-wrapper">
              <input type="file" style="display:none" ref="answerFileInput" @change="handleAnswerFileUpload" id="answerFile" />
              <button type="button" @click="triggerAnswerFileUpload" class="upload-button">
                <img src="@/assets/picture/upload.png" alt="上传图标" style="width: 20px; margin-right: 8px;" />上传附件
              </button>
              <span v-if="answerFileName" class="file-name">{{ answerFileName }}</span>
            </div>
            <div style="margin-bottom:5px">
              <button style="margin-right:40px" type="submit" class="submit-button">提交</button>
              <button type="button" class="back-button" @click="goBack">取消</button>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ApicreateAssignment, fetchClassDetails } from '@/services/api';
import AppBreadcrumb from '@/components/Breadcrumb.vue';
import QuillEditor from '@/components/QuillEditor.vue';

export default {
  name: 'NewAssignment',
  components: {
    AppBreadcrumb,
    QuillEditor
  },
  props: {
    semesterId: {
      type: [String, Number],
      required: true,
    }
  },
  setup(props) {
    const router = useRouter();
    const route = useRoute();
    const assignmentTitle = ref('');
    const assignmentContent = ref('');
    const assignmentAnswer = ref('');
    const selectedFileName = ref('');
    const answerFileName = ref('');
    const selectedFile = ref(null);
    const answerFile = ref(null);
    const techId = ref(null);
    const courseName = ref('课程'); // 默认显示 "课程"，之后获取实际名称

   const breadcrumbItemStyle = ref({
      textDecoration: 'none',
      color: 'gray',
      fontSize: '14px'
    });


    const breadcrumbs = computed(() => [
      { path: `/class-management/${props.semesterId}/TechNoti`, label: courseName.value },
      { path: `/class-management/${props.semesterId}/TechAssignments`, label: '图文作业' },
      { path: route.path, label: '新建详细' }
    ]);

    // 加载课程名称
    const loadCourseName = async () => {
      const techIdValue = techId.value;
      try {
        const response = await fetchClassDetails(props.semesterId,techIdValue);
        if (response.data.status === 1) {
          courseName.value = response.data.data.semester_name;
        } else {
          console.error('获取课程名称失败:', response.data.msg);
        }
      } catch (error) {
        console.error('加载课程名称失败:', error);
      }
    };

    onMounted(() =>{ 
      techId.value = localStorage.getItem('id');
      loadCourseName();
    });

    const handleFileUpload = (event) => {
      selectedFile.value = event.target.files[0];
      selectedFileName.value = event.target.files[0]?.name || '';
    };

    const handleAnswerFileUpload = (event) => {
      answerFile.value = event.target.files[0];
      answerFileName.value = event.target.files[0]?.name || '';
    };

    const triggerFileUpload = () => {
      document.getElementById('file').click();
    };

    const triggerAnswerFileUpload = () => {
      document.getElementById('answerFile').click();
    };

    const createAssignment = async () => {
  try {
    if (!assignmentTitle.value.trim()) {
      ElMessage.error('作业标题为必填项');
      return;
    }
    if (!assignmentContent.value.trim()) {
      ElMessage.error('作业内容为必填项');
      return;
    }
    if (!assignmentAnswer.value.trim()) {
      ElMessage.error('参考答案为必填项');
      return;
    }

    // Store the assignment title and status in localStorage before proceeding
    localStorage.setItem('hmk_title', assignmentTitle.value);
    localStorage.setItem('hmk_status', '新建'); // Assuming a default status like '新建'

    const formData = new FormData();
    formData.append('semester_id', props.semesterId);
    formData.append('hmk_title', assignmentTitle.value);
    formData.append('hmk_content', assignmentContent.value);
    formData.append('standard_answer', assignmentAnswer.value);
    if (selectedFile.value) formData.append('file', selectedFile.value);
    if (answerFile.value) formData.append('ans_file', answerFile.value);

    const response = await ApicreateAssignment(formData);
    if (response.data.status === 1) {
      const homeworkId = response.data.data;
      ElMessage.success('作业创建成功！');
      router.push({ name: 'AdvancedSettings', params: { homeworkId, semesterId: props.semesterId } });
    } else {
      ElMessage.error(`创建作业失败: ${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error('创建作业失败，请稍后重试。');
  }
};

    const goBack = () => {
      router.back();
    };

    return {
      assignmentTitle,
      assignmentContent,
      assignmentAnswer,
      selectedFileName,
      answerFileName,
      handleFileUpload,
      handleAnswerFileUpload,
      triggerFileUpload,
      triggerAnswerFileUpload,
      createAssignment,
      goBack,
      breadcrumbs,
      breadcrumbItemStyle
    };
  },
};
</script>


<style scoped>
.new-assignment {
  max-width: 75vw;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.required {
  color: red;
  margin-left: 5px;
}

input[type="text"] {
  width: 99%;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
}
.upload-button-wrapper{
  display: flex;
  align-items: center;
}
.upload-button {
  background-color: white;
  color: #333;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.upload-button:hover {
  background-color: #d8d8d8;
}

.file-name {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

.submit-button {
  background-color: #244382;
  color: #fff;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #1e3661;
}

.back-button {
  background-color: #f0f0f0;
  color: #333;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.back-button:hover {
  background-color: #d8d8d8;
}
</style>
